<!--
 * @Description: 添加,编辑员工弹窗组件
 * @version: 电子名片2.0
 * @Author: 付小清
 * @Date: 2020-12-04 10:44:50
 * @LastEditors: 尹鑫
 * @LastEditTime: 2020-12-18 16:22:41
-->

<template>
  <el-dialog
    width="570px"
    :title="_formData.genre == 'add' ? '添加员工' : '编辑员工'"
    :visible.sync="_isShow"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <el-form
      ref="refForm"
      style="padding-right: 40px"
      :model="_formData"
      label-width="120px"
      :rules="formVerify"
    >
      <el-form-item prop="userId" label="员工编码：">
        <el-input v-model="_formData.userId" :disabled="_formData.genre == 'edit' ? true : false" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="avatar" label="员工头像：">
        <el-upload
          class="userAvatar-uploader"
          :action="`${apiUrl}/oss/file-anon/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-show="_formData.avatar||imgUrl" :src="_formData.avatar||imgUrl" class="userAvatar">
          <i v-show="!Boolean(_formData.avatar||imgUrl)" class="el-icon-plus userAvatar-uploader-icon" />
        </el-upload>
        <div class="imgUploadTip">只可上传jpg图片且大小不超过2MB</div>
      </el-form-item>
      <el-form-item
        prop="username"
        label="员工账号："
      >
        <el-input v-model="_formData.username" autocomplete="off" />
      </el-form-item>
      <el-form-item
        prop="nickname"
        label="员工姓名："
      >
        <el-input v-model="_formData.nickname" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="mobile" label="员工手机：">
        <el-input v-model.number="_formData.mobile" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="gender" label="员工性别：">
        <el-radio-group v-model="_formData.gender">
          <el-radio :label="'1'">男</el-radio>
          <el-radio :label="'0'">女</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmit"> 提交 </el-button>
      <el-button @click="_isShow = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 接口
import { empUpdate, empAppend } from '@/api/system'
// import { companyList } from '@/api/organize'
export default {
  props: {
    // 弹窗显示
    show: {
      type: Boolean,
      default: false
    },
    // 表单数据
    formData: {
      type: Object,
      default: () => {
        return {
          genre: 'add', // add或者edit
          userId: '',
          avatar: '',
          nickname: '',
          username: '',
          mobile: '',
          gender: '1'
        }
      }
    }
  },
  data() {
    // 手机号码验证
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3-9][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      imgUrl: '',
      apiUrl: '',
      fileConfig: {
        headers: {}
      },
      formVerify: {
        userId: [
          {
            required: true,
            message: '请输入员工编码',
            trigger: ['blur', 'change']
          }
        ],
        avatar: [
          {
            required: true,
            message: '请上传用户头像',
            trigger: ['blur', 'change']
          }
        ],
        username: [
          {
            required: true,
            message: '请输入员工账号',
            trigger: ['blur', 'change']
          }
        ],
        nickname: [
          {
            required: true,
            message: '请输入员工姓名',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入员工手机',
            trigger: ['blur', 'change']
          },
          { validator: checkPhone, trigger: 'blur' }
        ],
        gender: [
          {
            required: true,
            message: '请输入员工性别',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  computed: {
    _isShow: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    },
    _formData: {
      get() {
        return this.formData
      },
      set(val) {
        this.$emit('update:formData', val)
      }
    }
  },
  created() {
    this.apiUrl = process.env.VUE_APP_BASE_API
  },
  methods: {
    closeDialog() {
      this.imgUrl = ''
      this._formData.genre = 'add'
      this._formData.userId = ''
      this._formData.avatar = ''
      this._formData.nickname = ''
      this._formData.username = ''
      this._formData.mobile = ''
      this._formData.gender = '1'
      this.$refs.refForm.resetFields()
    },
    handleAvatarSuccess(res, file) {
      this.imgUrl = res.data.url;
      this._formData.avatar = res.data.url;
      if ( res.data && res.data.url) {
        this.fileConfig.headers.files = [res.data.id]
        this.$message({ message: '图片上传成功', type: 'success' })
      } else {
        this.$message({ message: '图片上传失败', type: 'error' })
      }
      // if (res.data.isImg) {
      //   this.$message({ message: '图片上传成功', type: 'success' })
      // } else {
      //   this.$message({ message: '图片上传失败', type: 'error' })
      // }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('只能上传图片且只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return isJPG && isLt2M
    },
    onSubmit() {
      let Fun = empAppend // 添加员工
      if (this._formData.genre !== 'add') {
        Fun = empUpdate // 编辑员工
      }
      try {
        // 表单验证
        this.$refs.refForm.validate(async(valid) => {
          if (valid) {
            // 提交员工信息
            const { data, code } = await Fun({
              userId: this._formData.userId,
              username: this._formData.username,
              mobile: this._formData.mobile,
              gender: this._formData.gender,
              avatar: this._formData.avatar,
              nickname: this._formData.nickname
            }, this.fileConfig)
            // 操作成功处理
            if (code === 0 && data === true) {
              this._isShow = false
              this.$emit('refresh') // 刷新列表
              this.$store.dispatch('user/getCurrentUserInfo')
              if (this._formData.userId === JSON.parse(localStorage.getItem('userInfo')).userId) {
                this.$message({ message: '当前登录用户信息已被修改，请重新登录', type: 'warning' })
                this.$store.dispatch('user/logout')
                this.$router.push(`/login?redirect=${this.$route.fullPath}`)
              } else if (this._formData.genre === 'add') {
                this.$message({ message: '添加员工成功', type: 'success' })
              } else {
                this.$message({ message: '修改员工成功', type: 'success' })
              }
            } else {
              this.$message({ message: data, type: 'error' })
            }
          } else {
            console.log('error submit!!')
          }
        })
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .userAvatar-uploader .el-upload {
    border: 1px dashed #000000;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .userAvatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .userAvatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px solid #DCDFE6;
    border-radius: 5px;
  }
  .userAvatar {
    width: 100px;
    height: 100px;
    border-radius: 5px;
    display: block;
  }
  .imgUploadTip{
    font-size: 12px;
    color: rgb(163, 159, 159);
  }
</style>
